package com.open.capacity.user.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.open.capacity.commons.CodeEnum;
import com.open.capacity.user.dao.SysAuthorizeDao;
import com.open.capacity.user.dao.SysPermissionDao;
import com.open.capacity.user.dao.SysUserRelationDao;
import com.open.capacity.user.vo.SysRoleExcel;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.PageResult;
import com.open.capacity.commons.Result;
import com.open.capacity.model.system.SysRole;
import com.open.capacity.user.dao.SysRoleDao;
import com.open.capacity.user.service.SysRoleService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleDao sysRoleDao;
    @Autowired
    private SysAuthorizeDao authorizeDao;
    @Autowired
    private SysPermissionDao permissionDao;
    @Autowired
    private SysUserRelationDao userRelationDao;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(SysRole sysRole) {
        SysRole role = sysRoleDao.findByCode(sysRole.getCode());
        if (role != null) {
            throw new IllegalArgumentException("角色code已存在");
        }

        sysRole.setCreateTime(new Date());
        sysRole.setUpdateTime(sysRole.getCreateTime());

        sysRoleDao.save(sysRole);
        log.info("保存角色：{}", sysRole);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(SysRole sysRole) {
        sysRole.setUpdateTime(new Date());

        sysRoleDao.updateByOps(sysRole);
        log.info("修改角色：{}", sysRole);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteRole(Long id) {
        SysRole sysRole = sysRoleDao.findById(id);

        sysRoleDao.delete(id);
        authorizeDao.deleteByObjectId(id.toString());
        userRelationDao.deleteByObjectId(id.toString());

        log.info("删除角色：{}", sysRole);

    }


    @Override
    public SysRole findById(Long id) {
        return sysRoleDao.findById(id);
    }

    @Override
    public List<SysRole> findRoles(Map<String, Object> params) {
        return sysRoleDao.findList(params);
    }


    @Override
    public PageResult<SysRole> pageRoles(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);
        List<SysRole> list = sysRoleDao.findList(params);
        PageInfo<SysRole> pageInfo = new PageInfo(list);

        return PageResult.<SysRole>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }


    @Override
    public Result saveOrUpdate(SysRole sysRole, Long keyValue) {
        int i;
        if (keyValue == null || keyValue.equals(0)) {
            SysRole role = sysRoleDao.findByCode(sysRole.getCode());
            if (role != null) {
                return Result.failed("角色code已存在");
            }
            //sysRole.setId(UUIDUtils.getOriginalUUIDWithoutBar());
            sysRole.setFlag(1);
            sysRole.setCreateTime(new Date());
            sysRole.setUpdateTime(sysRole.getCreateTime());
            i = sysRoleDao.save(sysRole);
        } else {
            SysRole role = sysRoleDao.findByCode(sysRole.getCode());
            if (role != null && !role.getId().equals(keyValue)) {
                return Result.failed("角色code已存在");
            }
            sysRole.setId(keyValue);
            sysRole.setUpdateTime(new Date());
            i = sysRoleDao.updateByOps(sysRole);
        }
        return i > 0 ? Result.succeed("操作成功") : Result.failed("操作失败");
    }

    @Override
    public int auth(Long keyValue) {
        userRelationDao.updateStatus(keyValue.toString(), 1);
        authorizeDao.updateStatus(keyValue.toString(), 1);
        permissionDao.updateStatus(keyValue.toString(), 1);
        return 1;
    }

    @Override
    public List<SysRoleExcel> findExcels(Map<String, Object> params) {
        List<SysRole> list = sysRoleDao.findList(params);
        List<SysRoleExcel> result = new ArrayList<>();
        for (SysRole role : list) {
            SysRoleExcel excel = new SysRoleExcel();
            BeanUtils.copyProperties(role, excel);
            result.add(excel);
        }
        return result;
    }
}
